//
//  ShengJingViewController.m
//  JiuKuGospel
//
//  Created by jiukuyinyue on 15-8-18.
//  Copyright (c) 2015年 JiuKuForApp. All rights reserved.
//

#import "ShengJingViewController.h"
#import "JKSongsMessStatus.h"
#import "ShengJingMessageViewController.h"
#import "ShengJCustomCollectionViewCell.h"
#import "ShengJNumCollectionViewCell.h"
#import "ShengJingViewController+LCAVPlay.h"
#import "JKSongsMessStatus.h"
#import "NetworkTool+LCAVPlay.h"
#import "LCHistoryDataManager.h"
#import "TheHomeManager+Additions.h"
#import "NSString+Substring.h"

#define LEFT 20
#define HEIGHT 25

#define TOP_SCROLLVIEW 10

#define LIST_COUNT 2

@interface ShengJingViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong)UISegmentedControl * segment;

@property (nonatomic, strong)UICollectionView * shengjCollectionView;

@property (nonatomic, strong)UIScrollView * jiuyueScrollView;
@property (nonatomic, strong)UIScrollView * xinyueScrollView;

@property (nonatomic, strong)NSMutableArray * shengjingArr;
@property (nonatomic, strong)NSMutableArray * jiuyueArr;
@property (nonatomic, strong)NSMutableArray * xinyueArr;

@property (nonatomic, strong)NSMutableArray * tempDataArr;
@property (nonatomic, strong)NSMutableArray * tempXYDataArr;

@property (nonatomic, strong)UICollectionViewFlowLayout * flowLayout;
@property (nonatomic, strong)FMDatabase *db;
@property (nonatomic, strong)NSIndexPath * tempIndexPath;       //记录圣经位置
@property (nonatomic, assign)NSInteger countPlace;              //记录章节位置
@property (nonatomic, assign)NSInteger tempCount;

@property (nonatomic,strong) UIView * navView;
@end

@implementation ShengJingViewController{
    NSInteger _selectCell2Index;
    NSString *_selectName;
}

- (void)viewWillAppear:(BOOL)animated
{
    [LCFloatingWindow sharedInstance].hidden = NO;//安装AVPlay
    [super viewWillAppear:YES];
    
    [_shengjCollectionView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creareAVPlay];//安装播放器
    [self loadChapterData];//读取章节

    [self setupNavViewUI];
    [self setupRightBtnUI];
    [self setupSegmentUI];
    
//    [TheHomeManager shareTheHomeManager].tempIndexPath = [NSIndexPath indexPathForRow:<#(NSInteger)#> inSection:indexPathSection]
    self.tempIndexPath = [TheHomeManager shareTheHomeManager].tempIndexPath;
    NSLog(@"%zd ==== %zd", [TheHomeManager shareTheHomeManager].tempIndexPath.section, [TheHomeManager shareTheHomeManager].tempIndexPath.row);
    self.countPlace = [TheHomeManager shareTheHomeManager].tempIndexPath.row + 1;
    self.tempCount = self.numCount;
    
    
    [self setupNewShengJUI];
    
    [self.tempDataArr addObjectsFromArray:[TheHomeManager shareTheHomeManager].dataJiuyueArr];
    [self.tempXYDataArr addObjectsFromArray:[TheHomeManager shareTheHomeManager].dataXinyeuArr];
    
}
//导航栏
-(void)setupNavViewUI{
    UIView * navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 64)];
    _navView = navView;
    navView.backgroundColor = JK_HUISE_LINE_COLOR;
    [self.view addSubview:navView];
}

-(void)loadChapterData{
    //获取本地保存的位置
    NSString * str = [LCHistoryDataManager loadBibleTextTitleData];
    NSString *selectName = [str substringWithinBoundsLeft:@"约" right:@"("];
    NSInteger selectIndex = [[str substringWithinBoundsLeft:@"第" right:@"章"] integerValue];
    _selectName = selectName;
    _selectCell2Index = selectIndex;
}
//选择器
-(void)setupSegmentUI{
    NSArray * itemArr = [NSArray arrayWithObjects:self.nameStr, [NSString stringWithFormat:@"%zd", _selectCell2Index], nil];
    self.segment = [[UISegmentedControl alloc] initWithItems:itemArr];
    _segment.frame = CGRectMake((self.view.width-170)/2, 27, 170, 30);
    _segment.selectedSegmentIndex = self.selectIndex;
    _segment.tintColor = JK_RED_COLOR;
    [_segment setWidth:_segment.width/5*3 forSegmentAtIndex:0];
    [_segment addTarget:self action:@selector(changeUI:) forControlEvents:UIControlEventValueChanged];
    _segment.userInteractionEnabled = YES;
    [_navView addSubview:_segment];
}
//关闭按钮
-(void)setupRightBtnUI{
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(self.view.width-60, 20, 60, 44);
    [rightBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [rightBtn setTitleColor:JK_RED_COLOR forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(backTop) forControlEvents:UIControlEventTouchUpInside];
    [_navView addSubview:rightBtn];
}

- (void)setupShengJingUI
{
    CGFloat width = (self.view.width-(LIST_COUNT+1)*LEFT)/2;

    self.jiuyueScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, _segment.bottom+20, self.view.width, self.view.height-_segment.bottom-60-20)];
    [self.view addSubview:_jiuyueScrollView];
    NSLog(@"%zd", _jiuyueArr.count);
    NSInteger count = 0;
    for (int i = 0; i < (_jiuyueArr.count + 1)/2; i ++) {
        for (int j = 0; j < 2; j++) {
            UIImageView * tempImageView = [[UIImageView alloc] initWithFrame:CGRectMake((j+1)*LEFT+j*width, (i)*TOP_SCROLLVIEW+i*(width+30), width, width)];
            tempImageView.userInteractionEnabled = YES;
            tempImageView.tag = 800+count;

            NSString * tempImageStr = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%zd", count] ofType:@"png"];
            tempImageView.image = [UIImage imageWithContentsOfFile:tempImageStr];
            [_jiuyueScrollView addSubview:tempImageView];
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushShengjingMessage:)];
            [tempImageView addGestureRecognizer:tap];
            
            UILabel * tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(tempImageView.left, tempImageView.bottom, tempImageView.width, 30)];
            tempLabel.tag = 800+count+50;
            tempLabel.text = [[_jiuyueArr objectAtIndex:count] objectForKey:@"name"];
            
            
            [_jiuyueScrollView addSubview:tempLabel];
            if (count == _jiuyueArr.count-1) {
                break;
            }
            count++;
        }
    }
    
    _jiuyueScrollView.contentSize = CGSizeMake(self.view.width, ((_jiuyueArr.count + 1)/2)*(width+30+TOP_SCROLLVIEW));

    
}

- (void)setupNewShengJUI
{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.itemSize = CGSizeMake(self.view.width/5, self.view.width/5);
    _flowLayout.minimumInteritemSpacing = 0;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.headerReferenceSize = CGSizeMake(self.view.width, 30);

    self.shengjCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, self.view.width, self.view.height-64-60) collectionViewLayout:_flowLayout];
    _shengjCollectionView.delegate = self;
    _shengjCollectionView.dataSource = self;
    _shengjCollectionView.backgroundColor = [UIColor whiteColor];
    [_shengjCollectionView registerClass:[ShengJCustomCollectionViewCell class] forCellWithReuseIdentifier:@"collectionViewCell"];
    [_shengjCollectionView registerClass:[ShengJNumCollectionViewCell class] forCellWithReuseIdentifier:@"collectionViewCell2"];

    [_shengjCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:@"UICollectionElementKindSectionHeader" withReuseIdentifier:@"headerID"];

    [self.view addSubview:_shengjCollectionView];
    
}


- (void)changeUI:(UISegmentedControl *)segment
{
    
    NSLog(@"%zd", segment.selectedSegmentIndex);
    
    if (segment.selectedSegmentIndex == 0) {
        _flowLayout.headerReferenceSize = CGSizeMake(self.view.width, 30);
        [_shengjCollectionView reloadData];
    }
    
    if (segment.selectedSegmentIndex == 1) {
        
        _flowLayout.headerReferenceSize = CGSizeMake(self.view.width, 0);
        [_shengjCollectionView reloadData];
    }

}

#pragma mark - 推进到下一个界面
- (void)backTop{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 推进到下一个界面
- (void)pushShengjingMessage:(UITapGestureRecognizer *)tap{
    
    UIImageView * tempImageView = (UIImageView *)tap.view;
    if (_segment.selectedSegmentIndex == 0) {
        //推进到旧约详情
        NSInteger count = tempImageView.tag - 800;
        ShengJingMessageViewController * jiuyueVC = [[ShengJingMessageViewController alloc] init];
        jiuyueVC.titleStr = @"圣经";
        jiuyueVC.nameStr = [[_jiuyueArr objectAtIndex:count] objectForKey:@"name"];
        [self.navigationController pushViewController:jiuyueVC animated:YES];
    }

    if (_segment.selectedSegmentIndex == 1) {
        //推进到新约详情
        NSInteger count = tempImageView.tag - 900;
        ShengJingMessageViewController * xinyueVC = [[ShengJingMessageViewController alloc] init];
        xinyueVC.titleStr = @"圣经";
        xinyueVC.nameStr = [[_xinyueArr objectAtIndex:count] objectForKey:@"name"];
        [self.navigationController pushViewController:xinyueVC animated:YES];
        
    }

}



#pragma mark - 集合视图代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (_segment.selectedSegmentIndex == 1) {
        return 1;
    }
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_segment.selectedSegmentIndex == 1) {
        return _tempCount;
    }
    
    if (section == 0) {
        
        return self.tempDataArr.count;
    }
    if (section == 1) {
        return self.tempXYDataArr.count;
    }
    
        
    return self.tempDataArr.count;
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{

    UICollectionReusableView *tempView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerID" forIndexPath:indexPath];
    tempView.backgroundColor = JK_FENRED_COLOR;
    [tempView removeAllSubviews];
    if (_segment.selectedSegmentIndex == 1) {
        _flowLayout.headerReferenceSize = CGSizeMake(self.view.width, 0);
        return tempView;
    }

    
    UIImageView * tempImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.width/2-14-5, (tempView.height-14)/2, 14, 14)];
    tempImageView.image = [UIImage imageNamed:@"tips_open"];
    [tempView addSubview:tempImageView];
    
    UILabel * tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.width/2, 0, tempView.width/2, tempView.height)];
    tempLabel.font = FONT_14;
    [tempView addSubview:tempLabel];
    if (indexPath.section == 0) {
        tempLabel.text = @"旧约";
    }
    if (indexPath.section == 1) {
        tempLabel.text = @"新约";
    }
    
    return tempView;
    
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //给第几章 赋予颜色
    if (_segment.selectedSegmentIndex == 1) {
        ShengJNumCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionViewCell2" forIndexPath:indexPath];
        cell.messageStr = [NSString stringWithFormat:@"%zd", indexPath.row+1];
        if ((_selectCell2Index - 1) == indexPath.row) {//获取历史纪录
            cell.titleLabel.textColor = JK_RED_COLOR;//给章节赋予红色
        }
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = JK_HUISE_LINE_COLOR;
        cell.selectedBackgroundView = view;
        return cell;
    }
    
    ShengJCustomCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionViewCell" forIndexPath:indexPath];
//
//新约 给内容匹配的 赋予颜色 旧代码
    if (indexPath.section == 1) {
        cell.messageDic = [self.tempXYDataArr objectAtIndex:indexPath.row];
        if (indexPath.row == self.tempIndexPath.row && self.tempIndexPath.section == 1) {
            cell.titleLabel.textColor = JK_RED_COLOR;
            cell.nameLabel.textColor = JK_RED_COLOR;
        }
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = JK_HUISE_LINE_COLOR;
        cell.selectedBackgroundView = view;
        //点击纪录未实现
        return cell;
    }
    
//旧约 给内容匹配的 赋予颜色 新代码
    NSMutableDictionary *jiuyuemessageDic = [self.tempDataArr objectAtIndex:indexPath.row];
    cell.messageDic = jiuyuemessageDic;
    if (self.tempIndexPath.section == 0) {//indexPath.row == self.tempIndexPath.row &&
        if ([jiuyuemessageDic[@"name"] containsString:_selectName]) {
            cell.titleLabel.textColor = JK_RED_COLOR;
            cell.nameLabel.textColor = JK_RED_COLOR;
        }
    }
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = JK_HUISE_LINE_COLOR;
    cell.selectedBackgroundView = view;

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
 
    if (_segment.selectedSegmentIndex == 1) {
        [TheHomeManager shareTheHomeManager].tempIndexPath = self.tempIndexPath;
        [TheHomeManager shareTheHomeManager].tempCount = indexPath.row;

        //退出该界面  刷新歌词界面
        [self backTop];
#pragma mark -  刷新播放器  -
        [LSZSpecialPackaging addPlaylistWithArrayData:[TheHomeManager shareTheHomeManager].dataShengJingSongsArr];
#pragma mark -  播放器播放  -
        LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
        _LCPlayer.songs = playlistTest.allSongs;
        [_LCPlayer playAtIndex:[TheHomeManager shareTheHomeManager].tempCount isSelectPlay:YES];
        
#pragma mark -  刷新geci  -
        //        NSString * uid = [[[TheHomeManager shareTheHomeManager].dataShengJingSongsArr objectAtIndex:indexPath.row] objectForKey:@"id"];
//        [[TheHomeManager shareTheHomeManager] localShengJingLrc:_LCPlayer.playingSong.id];
        return;
    }
    
    
    self.tempIndexPath = indexPath;
    self.countPlace = 0;
    if (indexPath.section == 0) {
        _tempCount = [[[_tempDataArr objectAtIndex:indexPath.row] objectForKey:@"count"] integerValue];
        NSString * nameStr = [[_tempDataArr objectAtIndex:indexPath.row] objectForKey:@"name"];
        [_segment setTitle:nameStr forSegmentAtIndex:0];
        _selectCell2Index = 1;
        [_segment setTitle:[NSString stringWithFormat:@"%d", 1] forSegmentAtIndex:1];
        
        //查询更换歌曲信息
        [[TheHomeManager shareTheHomeManager] localShengJingSongMessage:[[self.tempDataArr objectAtIndex:_tempIndexPath.row] objectForKey:@"id"]];
    }
    if (indexPath.section == 1) {
        _tempCount = [[[_tempXYDataArr objectAtIndex:indexPath.row] objectForKey:@"count"] integerValue];
        NSString * nameStr = [[_tempXYDataArr objectAtIndex:indexPath.row] objectForKey:@"name"];
        [_segment setTitle:nameStr forSegmentAtIndex:0];
        _selectCell2Index = 1;
        [_segment setTitle:[NSString stringWithFormat:@"%d", 1] forSegmentAtIndex:1];

        //查询更换歌曲信息
        [[TheHomeManager shareTheHomeManager] localShengJingSongMessage:[[self.tempXYDataArr objectAtIndex:_tempIndexPath.row] objectForKey:@"id"]];
    }
    _segment.selectedSegmentIndex = 1;
    
    
    [_shengjCollectionView reloadData];
        
    
}

#pragma mark - 懒加载
- (NSMutableArray *)shengjingArr
{
    if (_shengjingArr == nil) {
        self.shengjingArr = [NSMutableArray array];
    }
    return _shengjingArr;
}

- (NSMutableArray *)jiuyueArr
{
    if (_jiuyueArr == nil) {
        self.jiuyueArr = [NSMutableArray array];
    }
    return _jiuyueArr;
}

- (NSMutableArray *)xinyueArr
{
    if (_xinyueArr == nil) {
        self.xinyueArr = [NSMutableArray array];
    }
    return _xinyueArr;
}

- (NSMutableArray *)tempDataArr
{
    if (_tempDataArr == nil) {
        self.tempDataArr = [NSMutableArray array];
    }
    return _tempDataArr;
}

- (NSMutableArray *)tempXYDataArr
{
    if (_tempXYDataArr == nil) {
        self.tempXYDataArr = [NSMutableArray array];
    }
    return _tempXYDataArr;
}

@end
